/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lwj;

import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.cluster.loadbalance.AbstractLoadBalance;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

/**
 * This class select one provider from multiple providers randomly.
 * You can define weights for each provider:
 * If the weights are all the same then it will use random.nextInt(number of invokers).
 * If the weights are different then it will use random.nextInt(w1 + w2 + ... + wn)
 * Note that if the performance of the machine is better than others, you can set a larger weight.
 * If the performance is not so good, you can set a smaller weight.
 */
public class RegionBalance extends AbstractLoadBalance {
    public static final String NAME = "regionbalance";
    @Override
    protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) {
        // Number of invokers
        int length = invokers.size();
        // Every invoker has the same weight?
        boolean sameWeight = true;
        List<Integer> idxList = new ArrayList<Integer>();
        String clientRegion = System.getProperty("clientRegion");
        for(int i = 0;i<invokers.size();i++){
            Invoker<T> tInvoker = invokers.get(i);
            System.out.println("URL : "+tInvoker.getUrl().toFullString());
            if(clientRegion.equals(tInvoker.getUrl().getParameter("serverRegion"))){
                idxList.add(i);
            }
        }
        if(idxList.size()>0){
            return invokers.get(idxList.get(ThreadLocalRandom.current().nextInt(idxList.size())));
        }
        return invokers.get(ThreadLocalRandom.current().nextInt(length));
    }

}
